#include "root.h"
#include<QTimer>

root::root(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::root)
{
    ui->setupUi(this);
}

root::~root()
{
    delete ui;
    delete dialog;
}

static int c=0; //输错密码的次数

void root::on_pushButton_clicked()
{
    string username = ui->lineEdit_User->text().toStdString();
    string passwd = ui->lineEdit_passwd->text().toStdString();

    auto users = this->getDialog()->getUserManager()->returnUsers();  // 返回一个users的map
    auto it = users.find(username);     // 返回对应username的User对象

    if (it == users.end()) {
        // 用户未找到
        QMessageBox msgBOX;
        msgBOX.setWindowTitle("Login");
        msgBOX.setText("User not found!");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);
        msgBOX.exec();
        return;
    }

    // 检查密码是否正确
    if (it->second.checkPassword(passwd))
    {
        //管理者登录的界面
        if(it->second.isAdminUser())
        {
            this->getDialog()->returnAdmin()->show();
            this->close();
        }
        else
        {
            QMessageBox msgBOX;
            msgBOX.setWindowTitle("warning");
            msgBOX.setText("Please proceed to the consumer login!");
            msgBOX.setStandardButtons(QMessageBox::Ok);
            msgBOX.exec();
        }
        return;
    }

    // 密码错误，增加计数器
    c++;

    // 检查是否输错了五次
    if (c==3)
    {
        // 显示错误消息并等待30秒
        ui->pushButton->setEnabled(false); // 禁用按钮
        ui->lineEdit_passwd->setEnabled(false); // 禁用密码输入框

        QMessageBox msgBOX;
        msgBOX.setText("You have input wrong password three times,please wait 30 seconds");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);

        QTimer* timer = new QTimer(this);
        connect(timer, &QTimer::timeout, [&, timer]() {
            c=0;  // 重置计数值
            timer->deleteLater();  // 清理定时器对象
            ui->pushButton->setEnabled(true); // 恢复按钮
            ui->lineEdit_passwd->setEnabled(true); // 恢复密码输入框
        });

        timer->start(30000);  // 30秒后执行定时器操作

        msgBOX.exec();
    }
    else
    {
        // 显示密码错误消息
        QMessageBox msgBOX;
        msgBOX.setText("Incorrect password!");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);
        msgBOX.exec();
    }

}



void root::on_pushButton_2_clicked()
{
    this->dialog->returnRegister()->show();

}

